<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>http://localhost:8080/up1img.html</h2>
<input type="file" id="file" style="display: none;">
<button id="btn">upload</button>
</body>
<script>
    let btn = document.querySelector('#btn')
    let file = document.querySelector('#file')

    btn.onclick = function () {
        file.click() // 调取系统选择图片的弹框
    }

    // 监听input的file变化值
    file.onchange = function (event) {
        let file = event.target.files[0]
        upload(file)
    }

    function upload(file) {
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/up1img', true)
        let formData = new FormData()
        formData.set('filename', file)
        xhr.send(formData)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert('success')
            }
        }
    }
</script>

</html>
